<template>
  <a-card :bordered="false">
    <detail-list title="订单信息">
      <detail-list-item term="订单编号">{{ orderInfo.numbering }}</detail-list-item>
      <detail-list-item term="订单状态">{{ statusMAP[orderInfo.status] && statusMAP[orderInfo.status].text }}
      </detail-list-item>
      <detail-list-item term="代理名称">{{ orderInfo.agent && orderInfo.agent.name }}</detail-list-item>
      <detail-list-item term="代理手机号">{{ orderInfo.agent && orderInfo.agent.phone }}</detail-list-item>
      <detail-list-item term="代理等级">{{ levelMap[orderInfo.agent && orderInfo.agent.level] &&
        levelMap[orderInfo.agent.level].text }}
      </detail-list-item>
      <detail-list-item term="订单创建时间">{{ orderInfo.created_at }}</detail-list-item>
    </detail-list>

    <a-divider/>

    <detail-list title="收件人信息">
      <detail-list-item term="姓名">{{ orderInfo.client_name }}</detail-list-item>
      <detail-list-item term="手机号">{{ orderInfo.client_phone }}</detail-list-item>
      <detail-list-item term="收货地址">
        {{ orderInfo.client_address }}
        <a-button type="link" @click="changeAddress()">修改地址</a-button>

        <a-modal
          title="修改地址"
          :confirm-loading="state.changeOrderAddressLoading"
          :visible="state.showChangeOrderAddressModal"
          @ok="handleChangeOrderAddress"
          @cancel="state.showChangeOrderAddressModal = false"
        >
          <a-form ref="form" :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
            <a-form-item
              label="新地址"
            >
              <a-input width="100%" v-decorator="['client_address']"/>
            </a-form-item>
          </a-form>
        </a-modal>
      </detail-list-item>
      <detail-list-item term="订单备注">{{ orderInfo.remark }}</detail-list-item>
    </detail-list>

    <a-divider/>

    <detail-list title="商品信息">
      <detail-list-item term="商品名称">{{ orderInfo.commodity_name }}</detail-list-item>
      <detail-list-item term="活动编号">{{ orderInfo.commodity_activity_id }}</detail-list-item>
      <detail-list-item term="供应商">{{ orderInfo.supplier && orderInfo.supplier.name }}</detail-list-item>
      <detail-list-item term="管理备注">{{ orderInfo.management_notes || '无' }}</detail-list-item>
      <detail-list-item term="商品总额">{{ orderInfo.commodity_price | formatAmount }}</detail-list-item>
      <detail-list-item term="运费">{{ orderInfo.freight | formatAmount }}</detail-list-item>
      <detail-list-item term="实付款">{{ orderInfo.total_amount | formatAmount }}</detail-list-item>

      <a-table
        rowKey="id"
        :columns="skuColumns"
        :data-source="skuData"
        :pagination="false"
      />
    </detail-list>

    <a-divider/>

    <detail-list title="发货信息">
      <OrderDelivery :id="parseInt($route.params.id)"></OrderDelivery>
    </detail-list>

    <a-divider/>

    <detail-list title="售后信息">
      <a-table
        rowKey="id"
        :columns="[
          {
            title: '售后编号',
            dataIndex: 'numbering',
            scopedSlots: { customRender: 'numbering' }
          },
          {
            title: '售后类型',
            customRender: (text, order) => {
              return afterSaleTypeMap[order.type].text
            }
          },
          {
            title: '申请时间',
            dataIndex: 'created_at'
          },
          {
            title: '状态',
            customRender: (text, order) => {
              return afterSaleOrderStatusMap[order.status].text
            }
          },
          {
            title: '金额',
            customRender: (text, order) => {
              return afterSaleOrderAmount(order)
            }
          }
        ]"
        :data-source="orderInfo.after_sale_order"
      >
        <span slot="numbering" slot-scope="text, record">
          <a @click="$router.push({ path: `/order/after-sale/info/${record.id}` })">{{ record.numbering }}</a>
        </span>
      </a-table>
    </detail-list>
  </a-card>
</template>

<script>
import { getOrderInfo, patchOrderReceivingInformation } from '@/api/order'
import DetailList from '@/components/DescriptionList/DescriptionList'
import CourierCompanySelection from '@/components/CourierCompanySelection/CourierCompanySelection'
import OrderDelivery from '@/components/OrderDelivery/OrderDelivery'
import { formatAmount } from '@/utils/util'
import pick from 'lodash.pick'

const DetailListItem = DetailList.Item

  const afterSaleTypeMap = {
    1: {
      text: '退货',
      reason: '退货'
    },
    2: {
      text: '重发货',
      reason: '重发货'
    },
    3: {
      text: '只退款',
      reason: '退款'
    },
    4: {
      text: '补偿',
      reason: '补偿'
    }
  }

  const StatusMAP = {
    1: {
      text: '待发货'
    },
    2: {
      text: '已发货'
    },
    3: {
      text: '已取消'
    }
  }

  const LevelMap = {
    1: {
      text: '群主'
    },
    2: {
      text: '精英'
    },
    3: {
      text: '大咖'
    }
  }

  const afterSaleOrderStatusMap = {
    1: {
      text: '待审核',
      icon: 'clock-o',
      iconColor: 'red',
      tips: '请耐心等待平台审核，感谢您的配合'
    },
    2: {
      text: '跟进中',
      icon: 'underway-o',
      iconColor: 'red',
      tips: '您的售后申请已由客服跟进中，请耐心等待。'
    },
    3: {
      text: '已通过',
      icon: 'checked',
      iconColor: 'green'
    },
    4: {
      text: '未通过',
      iconColor: 'red',
      icon: 'clear'
    },
    5: {
      text: '已取消',
      iconColor: 'red',
      icon: 'warning-o',
      tips: '您的售后申请已手动取消'
    }
  }

  export default {
    name: 'Info',
    components: { OrderDelivery, CourierCompanySelection, DetailList, DetailListItem },
    created () {
      this.getOrderInfo()
    },
    data () {
      return {
        orderInfo: {},
        form: this.$form.createForm(this),
        statusMAP: StatusMAP,
        levelMap: LevelMap,
        afterSaleTypeMap: afterSaleTypeMap,
        afterSaleOrderStatusMap: afterSaleOrderStatusMap,
        skuColumns: [
          {
            title: '进价（元）',
            dataIndex: 'purchase_price'
          },
          {
            title: '大咖价（元）',
            dataIndex: 'strongman_price'
          },
          {
            title: '精英价（元）',
            dataIndex: 'elite_price'
          },
          {
            title: '群主价（元）',
            dataIndex: 'group_owner_price'
          },
          {
            title: '直接奖励（元）',
            dataIndex: 'direct_invitation'
          },
          {
            title: '间接奖励（元）',
            dataIndex: 'indirect_invitation'
          },
          {
            title: '对外价格（元）',
            dataIndex: 'external_guide_price'
          },
          {
            title: '数量',
            dataIndex: 'amount'
          }
        ],
        skuData: [],
        state: {
          changeOrderAddressLoading: false,
          showChangeOrderAddressModal: false,
          isInitialed: false
        }
      }
    },
    methods: {
      getOrderInfo () {
        getOrderInfo(this.$route.params.id).then(res => {
          this.orderInfo = res
          // 执行过一次初始化后,就不再执行
          if (this.state.isInitialed) {
            return
          }
          this.state.isInitialed = true

          // 整理 SKU 的表头
          this.orderInfo.skus[0].sku_snapshot.values.reverse().forEach(
            sku => this.skuColumns.unshift({
              'title': sku.attribute.name,
              dataIndex: sku.attribute.id
            }))
          // 整理 SKU 数据
          this.orderInfo.skus.reverse().forEach(sku => {
            // sku 系统字段
            const sysField = pick(
              sku.sku_snapshot,
              ['direct_invitation', 'elite_price', 'entry_price', 'external_guide_price',
                'group_owner_price', 'indirect_invitation', 'strongman_price', 'purchase_price']
            )
            // 格式化
            Object.keys(sysField).forEach(field => {
              sysField[field] = formatAmount(sysField[field])
            })
            sysField.amount = sku.amount
            // sku 自定义数据
            sku.sku_snapshot.values.forEach(value => {
              sysField[value.attribute_id] = value.content
            })

            this.skuData.push(sysField)
          })
        })
      },
      afterSaleOrderAmount (order) {
        switch (order.type) {
          case 1:
            return formatAmount(order.after_sale_order_skus.reduce((total,
                                                                    curr) => total + (curr.amount * curr.unit_price), 0))
          case 2:
            return 0
          case 3:
            return formatAmount(order.refund_amount)
          case 4:
            return formatAmount(order.compensation)
        }
      },
      changeAddress () {
        this.state.showChangeOrderAddressModal = true
      },
      handleChangeOrderAddress () {
        const { form, state } = this
        state.changeOrderAddressLoading = true

        form.validateFields((err, values) => {
          if (!err) {
            patchOrderReceivingInformation(this.orderInfo.id, values)
              .then(_ => {
                this.getOrderInfo()
                this.$message.success('操作成功!')
              })
              .finally(_ => {
                state.changeOrderAddressLoading = false
                state.showChangeOrderAddressModal = false
              })
          } else {
            state.changeOrderAddressLoading = false
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
